let modal = weex.requireModule('modal')
let api = require('./api')
let Deferred = require('Deferred')
let navigator = require('./xnavigator')
let broadcastChannelKeys = require('./broadcast-channel-keys')
let BroadcastChannel = require('./broadcast-channel')
let webPageBc = new BroadcastChannel(broadcastChannelKeys.WEBPAGE_CLOSE)
let aliTradeService = weex.requireModule('aliTradeService')
module.exports = {
  auth () {
    var deferred = new Deferred()

    function doTopAuth () {
      api.top.auth.url().done(rs => {
        aliTradeService.couponPage({
          url: rs.data.authUrl,
          openType: 'auto'
        }, rs => {
          if (rs) {
            deferred.resolve()
          } else {
            modal.alert({message: '淘宝授权失败'})
            deferred.reject()
          }
        })
        // navigator.push('webpage.js?url=' + encodeURIComponent(rs.data.authUrl) + '&close_key=' + closeKey)
      })
    }

    if (aliTradeService.taobaoAuth) {
      aliTradeService.taobaoAuth(rs => {
        if (rs.ok) {
          doTopAuth()
        } else {
          modal.alert({message: '淘宝授权失败'})
          deferred.reject()
        }
      })
    } else {
      doTopAuth()
    }
    return deferred.promise()
  }
}
